
package us.hornerscorners.lollipop.hapi;

/*
* #%L
 * * LollipopRouter
 * *
 * %%
 * Copyright (C) 2013 - 2014 Jim Horner
 * *
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import java.net.URL;

import ca.uhn.hl7v2.hoh.api.IReceivable;

import ca.uhn.hl7v2.hoh.hapi.api.MessageSendable;

import ca.uhn.hl7v2.hoh.hapi.client.HohClientSimple;

import ca.uhn.hl7v2.model.Message;

import ca.uhn.hl7v2.protocol.ReceivingApplicationException;

import us.hornerscorners.lollipop.config.RoutingConfig;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-09-08
 * @author         Jim Horner
 */
public class HohClient implements IClient {

    /**
     * Method description
     *
     *
     * @param endpoint
     *
     * @return
     */
    @Override
    public boolean canHandle(String endpoint) {

        return endpoint.startsWith("http://");
    }

    /**
     * Method description
     *
     *
     *
     *
     * @param config
     * @param message
     *
     * @return
     *
     * @throws ReceivingApplicationException
     */
    @Override
    public Message sendMessage(RoutingConfig config, Message message)
            throws ReceivingApplicationException {

        IReceivable<Message> result = null;

        URL url = null;

        try {

            url = new URL(config.getEndpoint());

        } catch (Exception e) {

            throw new ReceivingApplicationException(e);
        }

        HohClientSimple client = new HohClientSimple(url);

        try {

            Integer responseTimeout = config.getResponseTimeout();

            if (responseTimeout != null) {
                client.setResponseTimeout(responseTimeout);
            }

            result = client.sendAndReceiveMessage(new MessageSendable(message));


        } catch (Exception e) {

            throw new ReceivingApplicationException(e);
        }

        if (result == null) {

            throw new ReceivingApplicationException("Response was null.");
        }

        return result.getMessage();
    }
}
